package com.baijiayun.live.ui.toolbox.lottery

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import android.text.Editable
import android.text.TextWatcher
import android.view.*
import android.widget.EditText
import android.widget.TextView
import com.baijiayun.live.ui.R
import com.baijiayun.live.ui.base.BasePadFragment
import com.baijiayun.live.ui.isMobileNumber
import com.baijiayun.livecore.models.LPLotteryResultModel
import com.baijiayun.liveuibase.utils.DisplayUtils
import com.baijiayun.liveuibase.utils.ThemeDataUtil
import com.baijiayun.liveuibase.widgets.dialog.ThemeMaterialDialogBuilder
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.bjy_fragment_lottery.*
import kotlinx.android.synthetic.main.bjy_item_lottery.view.*
import kotlinx.android.synthetic.main.bjy_layout_lottery_content.view.*
import kotlinx.android.synthetic.main.bjy_layout_lottery_content.view.tvLotteryTip
import kotlinx.android.synthetic.main.bjy_layout_lottery_content_edit.*
import kotlinx.android.synthetic.main.bjy_layout_lottery_content_edit.view.*

/**
 * Created by pengwenjian on 2020/8/25
 * Describe:
 */
class LotteryFragment : BasePadFragment() {

    private var lpLotteryResultModel: LPLotteryResultModel? = null
    private val STATE_EMPTY = 0    //未中奖
    private val STATE_EDIT = 1  //编辑页面
    private val STATE_LIST = 2  //查看中奖名单,未填写前点中奖名单
    private val STATE_DONE = 3  //完成
    private var status = STATE_EMPTY

    private var editLayout: View? = null
    private var listLayout: View? = null

    private val contentLayoutParams by lazy {
        val layoutParams = ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        layoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID
        layoutParams.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID
        layoutParams.startToStart = ConstraintLayout.LayoutParams.PARENT_ID
        layoutParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID
        layoutParams
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        view.setOnTouchListener { _, _ -> true }
        ivClose.setOnClickListener {
            when (status) {
                STATE_EMPTY, STATE_DONE -> routerViewModel.actionDismissLottery.value = Unit
                STATE_EDIT, STATE_LIST -> {
                    ThemeMaterialDialogBuilder(context!!)
                            .content(getString(R.string.live_close_not_edit_warn))
                            .positiveText(getString(R.string.live_confirm))
                            .negativeText(getString(R.string.live_cancel))
                            .negativeColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_dialog_negative_text_color))
                            .onPositive { materialDialog, _ ->
                                run {
                                    materialDialog.dismiss()
                                    routerViewModel.actionDismissLottery.value = Unit
                                }
                            }
                            .onNegative { materialDialog, _ -> materialDialog.dismiss() }
                            .canceledOnTouchOutside(true)
                            .build()
                            .show()
                }
            }
        }
        btnSubmit.setOnClickListener {
            when (status) {
                STATE_EMPTY ->{
                    status = STATE_DONE
                    switchStatePage()
                }
                STATE_DONE -> routerViewModel.actionDismissLottery.value = Unit
                STATE_EDIT -> if (checkEditContent()) {
                    submit()
                }
                STATE_LIST -> {
                    status = STATE_EDIT
                    switchStatePage()
                }
            }
        }
        //是否中奖
        var isWinner = false
        lpLotteryResultModel?.run {
            for (user in hitList) {
                if (routerViewModel.liveRoom.currentUser?.number == user.number) {
                    isWinner = true
                    break
                }
            }
        }
        if (!isWinner) {
            //未中奖 高度比较小235dp正常是278dp
            status = STATE_EMPTY
            switchStatePage()
        } else {
            editLayout = LayoutInflater.from(context).inflate(R.layout.bjy_layout_lottery_content_edit, lotteryContentLayout, false)
            lotteryContentLayout.addView(editLayout, contentLayoutParams)
            editLayout?.run {
                etPhone.addTextChangedListener(phoneWatcher)
                etUserName.addTextChangedListener(nameWatcher)
                tvWinList.setOnClickListener {
                    status = STATE_LIST
                    switchStatePage()
                }
            }
            listLayout = LayoutInflater.from(context).inflate(R.layout.bjy_layout_lottery_content, lotteryContentLayout, false)
            lotteryContentLayout.addView(listLayout, contentLayoutParams)
            lpLotteryResultModel?.run {
                for (user in hitList) {
                    val childView = View.inflate(context, R.layout.bjy_item_lottery, null)
                    childView.tvUserName.text = user.name
                    childView.tvGiftName.text = lotteryName
                    listLayout?.llContainer?.addView(childView)
                }
            }
            listLayout?.tvLotteryTip?.text = getString(R.string.live_lottery_bless_edit_tip)
            status = STATE_EDIT
            switchStatePage()
        }
    }

    private fun switchStatePage() {
        when (status) {
            STATE_EDIT -> {
                editLayout?.visibility = View.VISIBLE
                editLayout?.bringToFront()
                listLayout?.visibility = View.GONE
                ivSubmit.setImageResource(R.drawable.bjy_ic_text_submit)
            }
            STATE_LIST -> {
                listLayout?.visibility = View.VISIBLE
                listLayout?.bringToFront()
                editLayout?.visibility = View.GONE
                ivSubmit.setImageResource(R.drawable.bjy_ic_text_edit_info)
                ivLotteryHeader.setImageResource(R.drawable.bjy_ic_lottery_result)
            }
            STATE_DONE -> {
                val hits = lpLotteryResultModel?.hitList?.size?:0
                lotteryContentLayout.removeAllViews()
                if (hits > 0) {
                    val contentLayout = LayoutInflater.from(context).inflate(R.layout.bjy_layout_lottery_content, lotteryContentLayout, false)
                    lotteryContentLayout.addView(contentLayout, contentLayoutParams)
                    lpLotteryResultModel?.run {
                        for (user in hitList) {
                            val childView = View.inflate(context, R.layout.bjy_item_lottery, null)
                            childView.tvUserName.text = user.name
                            childView.tvGiftName.text = lotteryName
                            contentLayout.llContainer.addView(childView)
                        }
                    }
                    contentLayout.tvLotteryTip.text = getString(R.string.live_lottery_bless_edit_finish_tip)
                } else {
                    val textView = TextView(context)
                    textView.textSize = 12f
                    textView.text = getString(R.string.live_lottery_no_result)
                    textView.setTextColor(ContextCompat.getColor(context!!, R.color.live_lottery_text_color))
                    val layoutParams = ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                    layoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID
                    layoutParams.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID
                    layoutParams.startToStart = ConstraintLayout.LayoutParams.PARENT_ID
                    layoutParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID
                    lotteryContentLayout.addView(textView, layoutParams)
                    val textTitle = TextView(context)
                    textTitle.textSize = 12f
                    textTitle.text = getString(R.string.live_lottery_bless_edit_finish_tip)
                    textTitle.gravity = Gravity.CENTER
                    textTitle.setTextColor(ContextCompat.getColor(context!!, R.color.live_lottery_text_color))
                    val titleLayoutParams = ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                    titleLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID
                    titleLayoutParams.startToStart = ConstraintLayout.LayoutParams.PARENT_ID
                    titleLayoutParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID
                    titleLayoutParams.topMargin = DisplayUtils.dip2px(context!!,16f)
                    lotteryContentLayout.addView(textTitle, titleLayoutParams)
                }
                ivSubmit.setImageResource(R.drawable.bjy_ic_text_finish)
                ivLotteryHeader.setImageResource(R.drawable.bjy_ic_lottery_result)
            }
            STATE_EMPTY -> {
                ivLotteryHeader.setImageResource(R.drawable.bjy_ic_so_sorry)
                ivSubmit.setImageResource(R.drawable.bjy_ic_text_result)
                val layoutHeight = DisplayUtils.dip2px(context!!, 235f)
                layoutContainer.layoutParams.height = layoutHeight
                val ivHeaderParams = ivLotteryHeader.layoutParams as ConstraintLayout.LayoutParams
                ivHeaderParams.bottomMargin = layoutHeight - DisplayUtils.dip2px(context!!, 38f)
                val ivCloseParams = ivClose.layoutParams as ConstraintLayout.LayoutParams
                ivCloseParams.bottomMargin = layoutHeight - DisplayUtils.dip2px(context!!, 16f)
                val emptyLayout = LayoutInflater.from(context).inflate(R.layout.bjy_layout_lottery_empty, lotteryContentLayout, false)
                lotteryContentLayout.removeAllViews()
                lotteryContentLayout.addView(emptyLayout, contentLayoutParams)
            }
        }
    }

    private val nameWatcher: TextWatcher = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
            // do nothing
        }
        override fun afterTextChanged(s: Editable) {
            // do nothing
        }
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            tvUserNameWarn?.text = ""
        }
    }
    private val phoneWatcher: TextWatcher = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
            // do nothing
        }
        override fun afterTextChanged(s: Editable) {
            // do nothing
        }
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            tvPhoneWarn?.text = ""
        }
    }

    fun setResultModel(lpLotteryResultModel: LPLotteryResultModel) {
        this.lpLotteryResultModel = lpLotteryResultModel
    }

    /**
     * 提交
     */
    private fun submit() {
        val etUserName: EditText = view!!.findViewById(R.id.etUserName)
        val etPhone: EditText = view!!.findViewById(R.id.etPhone)
        lpLotteryResultModel?.run {
            routerViewModel.liveRoom.toolBoxVM.sendLotteryResult(beginTime,
                    etUserName.text.toString(),etPhone.text.toString())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe{
                        status = STATE_DONE
                        switchStatePage()
                    }
        }
    }

    private fun checkEditContent(): Boolean {
        val etUserName: EditText = view!!.findViewById(R.id.etUserName)
        val etPhone: EditText = view!!.findViewById(R.id.etPhone)
        val tvUserNameWarn: TextView = view!!.findViewById(R.id.tvUserNameWarn)
        val tvPhoneWarn: TextView = view!!.findViewById(R.id.tvPhoneWarn)
        if (etUserName.text.toString().isEmpty()) {
            tvUserNameWarn.text = getString(R.string.live_name_edit_tip)
        }
        if (etPhone.text.toString().isEmpty()) {
            tvPhoneWarn.text = getString(R.string.live_phone_edit_tip)
        } else {
            if (!isMobileNumber(etPhone.text.toString())) {
                tvPhoneWarn.text = getString(R.string.live_edit_error_tip)
            }
        }
        return tvPhoneWarn.text.toString().isEmpty() && tvUserNameWarn.text.toString().isEmpty()
    }

    override fun getLayoutId() = R.layout.bjy_fragment_lottery

    override fun onDestroyView() {
        super.onDestroyView()
        etPhone?.removeTextChangedListener(phoneWatcher)
        etUserName?.removeTextChangedListener(nameWatcher)
    }
}
